<template>
	<div>
		<cl-crud @load="onLoad">
			<template #slot-top-stats>
				<div class="header-box">
					<el-form :model="params" ref="params" label-width="100px">
						<el-form :model="params.child" ref="params2" label-width="100px">
							<el-form-item
								label="发送内容"
								prop="content"
								:rules="[
									{ required: true, message: '请输入推送内容', trigger: 'blur' }
								]"
							>
								<div>
									<el-input
										style="width:800px"
										placeholder="请输入推送内容"
										type="textarea"
										clearable
										v-model="params.child.content"
									></el-input>
								</div>
								<el-button size="mini" @click="addAsrc">添加链接</el-button>
								<el-button
									size="mini"
									:disabled="!params.child.content"
									@click="getNews(params.child.content)"
									>保存内容</el-button
								>
							</el-form-item>
							<el-form-item label="测试账号">
								<div style="color:red">
									（备注：选择公众号群发推送前，请先使用测试账号进行测试）
								</div>
								<el-checkbox-group v-model="params.child.account">
									<el-checkbox
										v-for="(item, index) in accountList"
										:key="index"
										:label="item.code"
									>
										<el-image
											style="width: 50px; height: 50px"
											:src="item.img"
										></el-image>
										{{ item.name }}</el-checkbox
									>
								</el-checkbox-group>
								<el-button size="mini" type="primary" @click="testPush('params2')"
									>提交测试推送</el-button
								>
							</el-form-item>
						</el-form>

						<el-form-item
							label="发送时间"
							prop="sendTime"
							:rules="[{ required: true, message: '选择日期时间', trigger: 'blur' }]"
						>
							<div style="color:red">
								（备注：至少大于当前时间1分钟）
							</div>
							<el-date-picker
								v-model="params.sendTime"
								type="datetime"
								placeholder="选择日期时间"
								:picker-options="pickerOptions0"
							></el-date-picker>
						</el-form-item>
						<el-form-item
							label="发送公众号"
							prop="public"
							:rules="[
								{
									type: 'array',
									required: true,
									message: '请至少选择一个公众号',
									trigger: 'change'
								}
							]"
						>
							<el-checkbox
								:indeterminate="isIndeterminate"
								v-model="checkAll"
								@change="checkAllChange"
								>全选</el-checkbox
							>
							<el-checkbox-group
								v-model="params.public"
								@change="handleCheckedCitiesChange"
							>
								<el-checkbox
									v-for="(item, index) in publicList"
									:key="index"
									:label="item.originalId"
									>{{ item.name }}</el-checkbox
								>
							</el-checkbox-group>
							<el-button size="mini" type="primary" @click="groupPush('params')"
								>添加</el-button
							>
						</el-form-item>
					</el-form>
				</div>
			</template>
			<template #table-column-status="{ scope }">
				<el-tag v-if="scope.row.status == 0">未发送</el-tag>
				<el-tag type="success" v-if="scope.row.status == 1">已发送</el-tag>
				<el-tag type="danger" v-if="scope.row.status == 2">已取消</el-tag>
				<el-tag type="info" v-if="scope.row.status == 3">发送中</el-tag>
			</template>
			<template #table-column-originalIds="{ scope }">
				<div v-for="(item, index) in scope.row.gzh" :key="index">
					<div v-if="item">{{ item.name }}</div>
				</div>
			</template>
		</cl-crud>
	</div>
</template>

<script>
import moment from 'moment';
import store from 'store';

export default {
	data() {
		return {
			contentTips: '<a href="这里换成链接">这里写要显示的文本</a>',
			params: {
				child: {
					content: store.get('jljNews') || '',
					account: ['oGeCmwWv84vEAB-3oNIJB1AqMv3Q'] //测试账号
				},
				sendTime: moment()
					.add('minutes', 5)
					.format('YYYY-MM-DD HH:mm:ss'),
				public: [] //公众号
			},
			accountList: [
				{
					name: '四处看风景',
					code: 'oGeCmwWv84vEAB-3oNIJB1AqMv3Q',
					img:
						'http://thirdwx.qlogo.cn/mmopen/Q3auHgzwzM57PEicI7oCUm3oXtuMzP8JDibM3Sj0ogM5ZXFGS7LO12IgOTW0kUb9hOSqD6atUpLPQ6BSaFssE9XA/132'
				},
				{
					name: '望穿秋水',
					code: 'oGeCmweoHrIb5kbo3Ag12SY6M2tA',
					img:
						'http://thirdwx.qlogo.cn/mmopen/ak0qlPkNNjSsiaBSOkicBe6um2bBib3fa19miarticYJkysmWne2CAGD2S6HKbuEpbKbicETt4ZsKEPA8rsH8Qa3sGe0b5jK4gLsuu/132'
				}
			],
			publicList: [],
			checkAll: false,
			isIndeterminate: false,
			pickerOptions0: {
				disabledDate(newDate) {
					return newDate.getTime() < Date.now();
				}
			}
		};
	},

	mounted() {},

	methods: {
		onLoad({ ctx, app }) {
			this.crud = app;
			ctx.service(this.$service.goodsMenagement.wechatCustomMsg)
				.set('table', {
					columns: [
						{
							label: '序号',
							type: 'index',
							align: 'center',
							width: 80
						},
						{
							label: '发送公众号',
							prop: 'originalIds',
							align: 'center'
						},
						{
							label: '内容',
							prop: 'msgContent',
							align: 'center',
							width: 120,
							'show-overflow-tooltip': true
						},
						{
							label: '是否发送',
							prop: 'status',
							align: 'center'
						},
						{
							label: '发送时间',
							prop: 'sendTime',
							align: 'center'
						},
						{
							label: '总发送',
							prop: 'sendTotal',
							align: 'center'
						},
						{
							label: '总成功',
							prop: 'sendSuccessTotal',
							align: 'center'
						},
						{
							label: '总失败',
							prop: 'sendFailTotal',
							align: 'center'
						}
					],

					op: {
						layout: ['delete']
					}
				})

				.set('layout', [
					['slot-top-stats'],
					['slot-top-mask'],
					['refresh-btn', 'slot-datepicker', 'flex1', 'search-key'],
					['data-table'],
					['flex1', 'pagination']
				])
				.on('refresh', async (params, { next, render }) => {
					let { list } = await next(params);
					let gzh = await this.$service.goodsMenagement.wechatConfig.list();
					this.publicList = gzh;
					list.map(item => {
						let arr = [];
						item.originalIds = item.originalIds.split(',');
						item.originalIds.map(i => {
							arr.push(gzh.filter(v => v.originalId == i)[0]);
						});
						item.gzh = arr;
					});
					render(list);
				})
				.done();

			app.refresh();
		},
		checkAllChange(val) {
			this.params.public = val
				? this.publicList.map(i => {
						return i.originalId;
				  })
				: [];
			this.isIndeterminate = false;
		},
		handleCheckedCitiesChange(value) {
			let checkedCount = value.length;
			this.checkAll = checkedCount === this.publicList.length;
			this.isIndeterminate = checkedCount > 0 && checkedCount < this.publicList.length;
		},
		testPush(val) {
			this.$refs[val].validate(data => {
				if (data) {
					let user = this.params.child.account.join();
					this.$service.goodsMenagement.wechatCustomMsg
						.test({
							content: this.params.child.content,
							users: user
						})
						.then(() => {
							this.$message.success('已提交测试');
						})
						.catch(err => {
							this.$message.error(err);
						});
				}
			});
		},
		groupPush(val) {
			this.$refs['params2'].validate(data1 => {
				if (data1) {
					this.$refs[val].validate(data2 => {
						if (data2) {
							let originalIds = this.params.public.join();
							let sendTime = moment(this.params.sendTime).format(
								'YYYY-MM-DD HH:mm:ss'
							);
							this.$service.goodsMenagement.wechatCustomMsg
								.add({
									originalIds,
									sendTime,
									msgContent: this.params.child.content,
									msgType: '0'
								})
								.then(() => {
									this.$message.success('添加成功');
									this.crud.refresh();
								})
								.catch(err => {
									this.$message.error(err);
								});
						}
					});
				}
			});
		},
		addAsrc() {
			this.params.child.content = this.params.child.content + this.contentTips;
		},
		// 保存发送内容
		getNews(val) {
			store.set('jljNews', val);
		}
	}
};
</script>
<style lang="scss" scoped>
.header-box {
	width: 100%;
}
</style>
